<template>
    <view class="seller_apply">
        <view class="seller_card">
            <view class="seller_form_item">
                <view class="seller_logo row">
                    <image
                        src="@/static/menu/logo.png"
                        mode="aspectFit"
                    ></image>
                    <text>Information</text>
                </view>
                <view class="seller_input row">
                    <text>Merchant Name</text>
                    <input
                        v-model="formData.name"
                        type="text"
                        placeholder="Please enter"
                    />
                </view>
                <view class="seller_cate row">
                    <text>Business Category</text>
                    <view class="cate_right row" @click.srop="onSheet">
                        <text style="margin-top: -6rpx">{{
                            categoryName
                        }}</text>
                        <u-icon
                            name="arrow-right"
                            color="#999999"
                            size="14"
                        ></u-icon>
                    </view>
                </view>
            </view>
        </view>
        <view class="seller_card">
            <view class="seller_form_item">
                <view class="item_header row">
                    <image src="@/static/required.png" mode=""></image>
                    <text>Shop photo</text>
                    <!-- <image src="@/static/required.png" mode=""></image> -->
                </view>
                <!-- <text class="item_gray">Click to upload shop details</text> -->
                <u-upload
                    :fileList="fileList"
                    uploadIconColor="#ffffff"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    multiple
                    :maxCount="9"
                ></u-upload>
            </view>
        </view>
        <view class="seller_card">
            <view class="seller_form_item">
                <view class="item_header row">
                    <image src="@/static/required.png" mode=""></image>
                    <text>business license</text>
                </view>
                <!-- <text class="item_gray">Click to upload shop details</text> -->
                <u-upload
                    :fileList="certificatesList"
                    width="150rpx"
                    height="114rpx"
                    uploadIcon="plus"
                    @afterRead="afterRead1"
                    @delete="deletePic1"
                    multiple
                    :maxCount="9"
                ></u-upload>
            </view>
        </view>
        <view class="seller_card">
            <view class="seller_form_item">
                <view class="item_header row">
                    <image src="@/static/required.png" mode=""></image>
                    <text>logo</text>
                </view>
                <u-upload
                    width="150rpx"
                    :fileList="logoList"
                    height="114rpx"
                    uploadIcon="plus"
                    :maxCount="1"
                    :multiple="false"
                    @afterRead="afterRead2"
                    @delete="deletePic2"
                ></u-upload>
            </view>
        </view>
        <view class="seller_card">
            <view class="seller_form_item">
                <view class="item_header row" style="padding-bottom: 0">
                    <image src="@/static/required.png" mode=""></image>
                    <text>Description</text>
                </view>
                <u--textarea
                    v-model="formData.introduce"
                    border="none"
                    style="padding: 18rpx 0"
                    placeholder="type text here"
                    count
                ></u--textarea>
            </view>
        </view>
        <view class="seller_card">
            <view class="seller_form_item">
                <view
                    class="item_header row"
                    style="justify-content: space-between"
                >
                    <text>
                        <image src="@/static/required.png" mode=""></image
                        >Choose Location
                    </text>
                    <u-icon
                        name="map"
                        color="#000000"
                        size="16"
                        @click="goWebView"
                    ></u-icon>
                </view>
                <!-- <input style="padding:16rpx 0;" v-model="formData.address" type="text" placeholder="Please enter the address" /> -->
                <p style="padding: 16rpx 0; color: #999">
                    {{ formData.address ? formData.address : "address" }}
                </p>
            </view>
            <view class="seller_form_item">
                <view class="item_header row">
                    <image src="@/static/required.png" mode=""></image>
                    <text>Phone</text>
                </view>
                <input
                    v-model="formData.phone"
                    type="number"
                    placeholder="Please enter your phone number"
                />
            </view>
            <view class="footer">
                <button @click.stop="handleSubmit">Confirm</button>
            </view>
        </view>
        <u-action-sheet
            :actions="cateList"
            @select="selectClick"
            :show="isSheet"
        ></u-action-sheet>
    </view>
</template>

<script>
import { shopCategories, policy, applyShop } from "@/lib/service";
import { showFailure, showMessage, showSuccess } from "@/lib/helper";
import { getShopDetail } from "@/lib/business";
export default {
    data() {
        return {
            fileList: [],
            certificatesList: [],
            cateList: [],
            logoList: [],
            categoryName: "Please select",
            isSheet: false,
            formData: {
                name: "",
                imgurls: "",
                certificates: "",
                logo: "",
                category: "",
                address: "",
                longitude: "",
                latitude: "",
                introduce: "",
                phone: "",
            },
        };
    },
    onLoad() {
        this.formData.phone = this.userInfo.phone;
        this.handleCate();
        // this.getInfor();
        console.log(this.userInfo, "getInfor");
        // #ifdef APP-PLUS
        uni.$on("googleMsg", this.handleMessage1);
        // #endif
        // #ifdef H5
        window.addEventListener("message", this.handleMessage);
        // #endif
    },
    computed: {
        userInfo() {
            return this.$store.state.user;
        },
    },
    methods: {
        getInfor() {
            getShopDetail().then((res) => {
                if (res.statusCode == 0) {
                    this.formData = res.data;
                }
            });
        },
        handleMessage(event) {
            if (!event.data.data) return;
            // 处理接收到的数据
            const { action, addresstxt, longitude, latitude } =
                event.data.data.arg;
            console.log("Received data from WebView-H5:", event.data);
            if (action === "chooseaddress") {
                this.formData.address = addresstxt;
                this.formData.longitude = longitude; //经度
                this.formData.latitude = latitude; //纬度
            }
        },
        handleMessage1(event) {
            if (!event.action) return;
            // 处理接收到的数据
            const { action, addresstxt, longitude, latitude } = event;
            console.log("Received data from WebView-APP:", event);
            if (action === "chooseaddress") {
                this.formData.address = addresstxt;
                this.formData.longitude = longitude; //经度
                this.formData.latitude = latitude; //纬度
            }
        },
        handleCate() {
            shopCategories()
                .then((res) => {
                    if (res.statusCode == 0) {
                        this.cateList = res.data.list;
                    }
                })
                .catch((res) => {});
        },
        onSheet() {
            this.isSheet = true;
        },
        deletePic(event) {
            this.fileList.splice(event.index, 1);
        },
        deletePic1(e) {
            this.certificatesList.splice(event.index, 1);
        },
        deletePic2(e) {
            this.logoList.splice(event.index, 1);
        },
        // 新增图片
        async afterRead(event) {
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList.length;
            lists.map((item) => {
                this.fileList.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i]);
                let item = this.fileList[fileListLen];
                this.fileList.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        async afterRead1(event) {
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.certificatesList.length;
            lists.map((item) => {
                this.certificatesList.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i]);
                let item = this.certificatesList[fileListLen];
                this.certificatesList.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        // 上传logo
        async afterRead2(event) {
            let lists = [].concat(event.file);
            let fileListLen = this.logoList.length;
            lists.map((item) => {
                this.logoList.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i]);
                let item = this.logoList[fileListLen];
                this.logoList.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        uploadFilePromise(file) {
            let name = file.name ? file.name : file.url.split("/").pop();
            return new Promise((resolve, reject) => {
                policy("house", name).then((res) => {
                    let a = uni.uploadFile({
                        url: res.data.signedUrl, // 仅为示例，非真实的接口地址
                        filePath: file.url,
                        name: "file",
                        success: (res) => {
                            try {
                                var data = JSON.parse(res.data);
                                resolve(data.data);
                            } catch (e) {
                                console.log(e);
                            }
                        },
                    });
                });
            });
        },
        selectClick(e) {
            this.categoryName = e.name;
            this.formData.category = e.id;
            this.isSheet = false;
        },
        goWebView() {
            let language = uni.getStorageSync("language") || "en";
            //该功能只能真机使用 仅限于 App  .nvue
            // #ifdef APP-PLUS
            uni.navigateTo({
                url:
                    "/pages/submit/searchLocationApp?type=add&language=" +
                    language,
            });
            // #endif

            // #ifdef H5
            uni.navigateTo({
                url:
                    "/pages/submit/searchLocation?type=add&language=" +
                    language,
            });
            // #endif
        },
        validateFormWithDetails(data) {
            const fieldNames = {
                name: "Merchant Name",
                imgurls: "Shop photo",
                certificates: "business license",
                logo: "Logo",
                category: "Business Category",
                address: "address",
                longitude: "longitude",
                latitude: "latitude",
                introduce: "Description",
                phone: "phone",
            };

            for (let key in data) {
                if (data.hasOwnProperty(key)) {
                    if (
                        data[key] === null ||
                        data[key] === undefined ||
                        data[key] === ""
                    ) {
                        return {
                            isValid: false,
                            field: key,
                            fieldName: fieldNames[key] || key,
                            message: `${
                                fieldNames[key] || key
                            } Cannot be empty`,
                        };
                    }
                }
            }

            return {
                isValid: true,
            };
        },
        handleSubmit() {
            if (this.fileList.length > 0) {
                this.formData.imgurls = this.fileList
                    .map((item) => item.url)
                    .join(",");
            }
            if (this.certificatesList.length > 0) {
                this.formData.certificates = this.certificatesList
                    .map((item) => item.url)
                    .join(",");
            }
            if (this.logoList.length > 0) {
                this.formData.logo = this.logoList
                    .map((item) => item.url)
                    .join(",");
            }

            let validateResult = this.validateFormWithDetails(this.formData);
            if (!validateResult.isValid) {
                uni.showToast({
                    title: validateResult.message,
                    icon: "none",
                });
                return;
            }
            uni.showLoading();
            applyShop(this.formData)
                .then((res) => {
                    uni.setStorageSync("location", null);
                    uni.showToast({
                        title: "The application has been submitted. Please wait patiently for the review",
                        icon: "none",
                    });
                    uni.hideLoading();
                    setTimeout(() => {
                        uni.switchTab({
                            url: "/pages/user/user",
                        });
                    }, 2000);
                })
                .catch((err) => {
                    uni.hideLoading();
                    showFailure();
                });
        },
    },
};
</script>

<style lang="scss" scoped>
.seller_apply {
    padding: 36rpx 28rpx;
    padding-bottom: 140rpx;

    .seller_card {
        border-radius: 22.9rpx;
        padding: 16rpx 20rpx;
        box-shadow: 0rpx 0rpx 19.08rpx rgba(239, 239, 239, 0.79);
        margin-bottom: 24rpx;

        .seller_form_item {
            .seller_logo {
                text {
                    font-family: PingFang SC;
                    font-weight: 500;
                    color: #272727;
                    font-size: 30rpx;
                }

                image {
                    width: 42rpx;
                    height: 42rpx;
                    margin-right: 10rpx;
                    // background: #eeeeee;
                    border-radius: 50%;
                }
            }

            .seller_input {
                margin-top: 16rpx;

                input {
                    padding-left: 20rpx;
                }

                text {
                    font-family: PingFang SC;
                    color: #a5a5a5;
                    font-size: 28rpx;
                }
            }

            .seller_cate {
                margin-top: 16rpx;
                justify-content: space-between;

                text {
                    font-family: PingFang SC;
                    color: #a5a5a5;
                    font-size: 26rpx;
                }
            }

            .item_header {
                padding-bottom: 16rpx;

                text {
                    font-family: PingFang SC;
                    font-weight: 500;
                    color: #272727;
                    font-size: 24rpx;
                }

                image {
                    width: 14rpx;
                    height: 12rpx;
                    margin-right: 8rpx;
                }
            }

            .item_gray {
                font-family: PingFang SC;
                color: #939393;
                font-size: 22rpx;
                display: block;
                padding-bottom: 16rpx;
            }
        }
    }
}

.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 30rpx 0;
    background: #ffffff;

    button {
        width: 92%;
        border-radius: 50rpx;
        height: 92rpx;
        background: #fc721a;
        line-height: 92rpx;
        font-family: Montserrat;
        font-weight: 500;
        color: #ffffff;
        font-size: 30rpx;
        text-align: center;
        padding: 0;
        margin: 0 4%;
    }
}
</style>
